package com.oa.crm.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.mdp.core.service.BaseService;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.oa.crm.common.CrmUtils;
import com.oa.crm.entity.Customer;
import com.oa.crm.entity.CustomerContacter;
import com.oa.crm.enums.CustomerOpertionEnum;
import com.oa.crm.mapper.CustomerMapper;
import com.oa.crm.vo.CustomerAddVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月8日
 */
@Service
public class CustomerService extends BaseService<CustomerMapper, Customer> {
    static Logger logger = LoggerFactory.getLogger(CustomerService.class);

    /**
     * 请在此类添加自定义函数
     */
    @Autowired
    private CustomerContacterService customerContacterService;

    @Autowired
    private CustomerOpertionService customerOpertionService;

    @Autowired
    private CustomerShareService customerShareService;


    /**
     * 自定义查询，支持多表关联
     *
     * @param page 分页条件
     * @param ew   一定要，并且必须加@Param("ew")注解
     * @param ext  如果xml中需要根据某些值进行特殊处理，可以通过这个进行传递，非必须，注解也可以不加
     * @return
     */
    public List<Map<String, Object>> selectListMapByWhere(IPage page, QueryWrapper ew, Map<String, Object> ext) {
        return baseMapper.selectListMapByWhere(page, ew, ext);
    }

    public void updateCustomerEvaluation(Map<String, Object> editParams) {
        baseMapper.updateCustomerEvaluation(editParams);
    }

    @Transactional
    public void insertCustomer(CustomerAddVo customerAddVo, String ipAddress) throws JsonProcessingException {
        User user = LoginUtils.getCurrentUserInfo();
        Date nowDate = new Date();
        //1.添加客户表
        Customer customer = customerAddVo.getCustomer();
        customer.setCreateUserId(user.getUserid());
        customer.setCreateUserName(user.getUsername());
        customer.setCreateTime(nowDate);
        customer.setUpdateUserId(user.getUserid());
        customer.setUpdateUserName(user.getUsername());
        customer.setUpdateTime(nowDate);
        customer.setIsAttention("0");
        //设置门户状态为 1已开通 0未开通
        customer.setPortalStatus("0");
        //设置最后联系时间
        customer.setLastContactTime(nowDate);
        customer.setBranchId(user.getBranchId());
        this.insert(customer);

        //2.添加客户联系人表
        this.insertCustomerContacter(customerAddVo.getContacterList(), customer, user);

        //3.添加操作记录表
        customerOpertionService.addOperHistory(customer.getCustomerId(), CrmUtils.obj2Json(CrmUtils.paramsTransferOper("", "新建", "", "")), CustomerOpertionEnum.OPER_CREATE.getCode(), ipAddress);

        //4.添加权限表，默认创建客户经理人有查看编辑权限。
        customerShareService.insertAddCustomerShare(customer.getCustomerId(), customer.getManagerUserId(), customer.getManagerUserName());
    }

    @Transactional
    public void insertCustomerContacter(List<CustomerContacter> contacterList, Customer customer, User user) {
        for (CustomerContacter customerContacter : contacterList) {
            customerContacter.setContacterId(customerContacterService.createKey("contacterId"));
            customerContacter.setBranchId(user.getBranchId());
            customerContacter.setCustomerId(customer.getCustomerId());
            customerContacter.setCustomerName(customer.getCustomerName());
        }
        customerContacterService.batchInsert(contacterList);
    }

    /**
     * 修改客户的关注状态
     *
     * @param customer
     */
    public void isAttention(Map<String, Object> customer) {
        baseMapper.updateCustomerAttention(customer);
    }


    /**
     * 获取最新的客户10个
     *
     * @param customer
     * @return
     */
    public List<Map<String, Object>> getNewestCustomer(Map<String, Object> customer) {
        User user = LoginUtils.getCurrentUserInfo();
        customer.put("branchId", user.getBranchId());
        return baseMapper.getCustomerLimit10(customer);
    }

    /**
     * 修改客户内容
     *
     * @param customerAddVo
     */
    @Transactional
    public void editCustomer(CustomerAddVo customerAddVo, String ipAddress) throws IllegalAccessException, JsonProcessingException {
        Customer customer = customerAddVo.getCustomer();
        User user = LoginUtils.getCurrentUserInfo();
        Customer oldCustomer = this.selectOneObject(customer);
        String customerId = customer.getCustomerId();

        //1.修改main表
        customer.setUpdateUserId(user.getUserid());
        customer.setUpdateUserName(user.getUsername());
        customer.setUpdateTime(new Date());
        this.updateByPk(customer);

        //修改联系人
        //新添加的联系人数据
        List<CustomerContacter> insertData = new ArrayList<>();

        //更新的联系人数据
        List<CustomerContacter> updateData = new ArrayList<>();

        //全部数据
        List<CustomerContacter> allData = customerAddVo.getContacterList();

        for (CustomerContacter contacter : allData) {
            if (StringUtils.isEmpty(contacter.getContacterId())) {
                insertData.add(contacter);
            } else {
                updateData.add(contacter);
            }
        }

        if (!CollectionUtils.isEmpty(insertData)) {
            //3.添加联系人
            this.insertCustomerContacter(insertData, customer, user);
        }

        //4.修改联系人
        customerContacterService.batchUpdate(updateData);

        //5.添加操作记录
        //--1.获取两边修改过后的值
        List<Map<String, Object>> historys = CrmUtils.getNotEqualsParams(oldCustomer, customer);
        ObjectMapper mapper = new ObjectMapper();
        String change = mapper.writeValueAsString(historys);
        customerOpertionService.addOperHistory(customerId, change, "update", ipAddress);
    }

    /**
     * 查询客户相对应的联系人
     *
     * @param customerList
     * @return
     */
    public List<Map<String, Object>> selectCustomerContacter(List<Map<String, Object>> customerList) {
        List<String> customerIds = Lists.newArrayList();
        for (Map<String, Object> stringObjectMap : customerList) {
            customerIds.add((String) stringObjectMap.get("customerId"));
        }
        if (CollectionUtils.isEmpty(customerIds)) return customerList;
        //查询联系人
        List<CustomerContacter> customerContacters = customerContacterService.selectContacterByCpIds(customerIds);
        for (Map<String, Object> stringObjectMap : customerList) {
            List<CustomerContacter> contacterList = Lists.newArrayList();
            for (CustomerContacter contacter : customerContacters) {
                if (stringObjectMap.get("customerId").equals(contacter.getCustomerId())) {
                    contacterList.add(contacter);
                }
            }
            stringObjectMap.put("contacterList", contacterList);
        }
        return customerList;
    }

    public List<Map<String, Object>> selectCustomerByAuthority(Map<String, Object> params) {
        return baseMapper.selectCustomerByAuthority(params);
    }
}

